/*
 * @Description: 创建广告
 * @Author: kanglin
 * @Date: 2018-06-20 10:05:57
 * @Copyright: Created by Panxsoft.
 */

<style lang="less" scoped rel="stylesheet/less" type="text/less" >
    .advert-create{
		  height: 74vh;

      .device__account{
        max-width: 400px;
      }

      .redirect_img_thumb {
        height: 50px;
        vertical-align: middle;
      }
    }
</style>

<template>
	<div class="advert-create">
		<Row
			type="flex"
			justify="start">
			<i-col push="1">
				<Form
					ref="formValidate"
					:model="formValidate"
					:rules="ruleValidate"
					:label-width="labelWidth(110, 150)"
					name="create__form"
					class="device__account">
					<FormItem
						:label="$t('advert.name')"
						prop="name">
						<i-input
							v-model="formValidate.name"
							:placeholder="$t('advert.please_enter_name')"
							name="create__name"/>
					</FormItem>

					<Form-item
						:label="$t('advert.device_account')"
						:placeholder="$t('advert.please_select_device')"
						prop="device_account_ids">
						<Select
							v-model="formValidate.device_account_ids"
							class="device__account"
							name="create__device_account_ids"
							multiple>
							<OptionGroup
								v-for="store in storeDevices"
								:key="store.id"
								:label="store.name">
								<Option
									v-for="device in store.device_accounts"
									:value="device.id"
									:key="device.id">{{ device.account }}
								</Option>
							</OptionGroup>
						</Select>
					</Form-item>

					<Form-item
						:label="$t('advert.media_type')"
						prop="advert_type_id">

						<RadioGroup v-model="formValidate.advert_type_id">
							<Radio :label="image">
								<Icon type="images" />
								<span>{{ $t('advert.image') }}</span>
							</Radio>
							<Radio :label="video">
								<Icon
									type="social-youtube"
									name="create__video"/>
								<span>{{ $t('advert.video') }}</span>
							</Radio>
						</RadioGroup>

					</Form-item>

					<Form-item
						:label="$t('advert.media')"
						prop="url">
						<!-- bos上传按钮组件 -->
						<bos-upload
							ref="bos_upload"
							:bos-config="bosConfig"
							:accept="accept"
							:auto-start="true"
							:file-type-reg-exp="fileTypeRegExp"
							:tips="$t('advert.select_file')"
							name="create__media"
							@post-init="init"
							@progress="changeProgress"
							@error="handleError"
							@post="handlePostComplete"
							@validate="isValidateVideo"/>
						<p>{{ uploadTips }}</p>
					</Form-item>

					<Form-item
						v-if="isAdvertTypeImage()"
						:label="$t('advert.play_second')"
						prop="play_second">
						<InputNumber
							:max="60*60*12"
							:min="1"
							v-model="formValidate.play_second"
							name="create__play_second"/>
					</Form-item>

					<Form-item
						v-if="isAdvertTypeImage()"
						:label="$t('advert.redirect_type')"
						prop="redirect_type">

						<Select
							v-model="formValidate.redirectable_type"
							:placeholder="$t('common.none')"
							clearable
							name="create__redirectable_type"
							@on-change="formValidate.redirectable_id = 0"
						>
							<Option
								v-for="redirect_type in redirect_types"
								:value="redirect_type.id"
								:key="'redirect_type' + redirect_type.id">{{ redirect_type.name }}
							</Option>
						</Select>
					</Form-item>

					<!-- 选整妆 -->
					<Form-item
						v-if="packSelectionVisible()"
						:label="$t('advert.redirect_pack')"
						required
						prop="redirectable_id">

						<Select
							v-model="formValidate.redirectable_id"
							name="create__redirect_pack_id"
							filterable
						>
							<Option
								v-for="pack in packs"
								:value="pack.id"
								:key="'pack' + pack.id"
								:label="pack.name"
							>
								<img
									:src="pack.thumb"
									class="redirect_img_thumb">
								<span>{{ pack.name }}</span>
							</Option>
						</Select>
					</Form-item>

					<!-- 选单品 -->
					<Form-item
						v-if="assetSelectionVisible()"
						:label="$t('advert.redirect_product')"
						required
						prop="redirectable_id">

						<Select
							v-model="formValidate.redirectable_id"
							name="create__redirect_product_id"
							filterable
						>
							<Option
								v-for="product in products"
								:value="product.id"
								:key="'product' + product.id"
								:label="product.name">
								<img
									:src="product.thumb_image && product.thumb_image.key"
									class="redirect_img_thumb">
								<span>{{ product.name }}</span>
							</Option>
						</Select>
					</Form-item>

					<!-- 跳转网址 -->
					<Form-item
						v-if="urlInputVisible()"
						:label="$t('advert.redirect_url')"
						required
						prop="redirect_url">

						<i-input
							v-model="formValidate.redirect_url"
							:placeholder="$t('advert.please_enter_url')"
							name="create__redirect_url"/>
					</Form-item>

					<Form-item>
						<Button
							type="primary"
							name="create__submit"
							@click="handleSubmit('formValidate')">{{ $t('common.submit') }}</Button>
						<Button
							type="ghost"
							name="create__reset"
							style="margin-left: 8px"
							@click="handleReset('formValidate')">{{ $t('common.reset') }}</Button>
					</Form-item>
				</Form>
			</i-col>
		</Row>
	</div>
</template>


<script>
import bosUpload from 'src/views/component/bosupload';
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { mapMutations } from 'vuex';
import { isUrlValidate, deleteEmptyValue } from 'src/utils/utils';

const [ADVERT_TYPE_ID_IMAGE, ADVERT_TYPE_ID_VIDEO] = [1, 2]; // 常量
const [REDIRECTABLE_TYPE_PACK, REDIRECTABLE_TYPE_PRODUCT, REDIRECTABLE_TYPE_URL] = ['Pack', 'Product', 'Url'];

export default {
	name: 'AdvertCreate',
	components: {
		bosUpload,
	},
	mixins: [labelWidthMixin],
	props: {
		bosConfig: {
			type: Object,
			required: true,
		},
		storeDevices: {
			type: Array,
			required: true,
		},
		post: {
			type: Function,
			required: true,
		},
		packs: {
			type: Array,
			required: true,
		},
		products: {
			type: Array,
			required: true,
		},
	},
	data() {
		return {
			formValidate: {
				advert_type_id: ADVERT_TYPE_ID_IMAGE, // 广告类别id 1 图片 2 视频
				name: null, // 广告名称
				content_key: null, // 广告内容 bos的key值 ，create方法获取bos 配置
				play_second: 15, // 播放时长
				device_account_ids: [], // 设备id，create 方法获取
				redirectable_type: '', // 跳转类型
				redirectable_id: 0, // 跳转整妆ID
				redirect_url: '', // 跳转网址的地址
			}, // 新增表单数据
			ruleValidate: { // 表单验证规则
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('advert.name') }),
						trigger: 'blur',
					},
				],
				play_second: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.play_second') }),
						trigger: 'blur',
					},
				],
				device_account_ids: [
					{
						required: true,
						type: 'array',
						min: 1,
						message: this.$t('validate.required', { field: this.$t('advert.device_account') }),
						trigger: 'change',
					},
				],
				redirectable_id: [
					{
						validator: this.validateRedirectId.bind(this),
					},
				],
				redirect_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl.bind(this),
				}],
			},
			image: ADVERT_TYPE_ID_IMAGE, // 指定当前选项的 value 值
			video: ADVERT_TYPE_ID_VIDEO, // 指定当前选项的 value 值
			accepts: { // 设置 bos accept
				[ADVERT_TYPE_ID_IMAGE]: 'image/gif, image/jpeg, image/png',
				[ADVERT_TYPE_ID_VIDEO]: 'video/mp4',
			},
			regExps: { // 设置 校验文件类型的正则
				[ADVERT_TYPE_ID_IMAGE]: /(image\/gif|image\/jpeg|image\/png)/i,
				[ADVERT_TYPE_ID_VIDEO]: /video\/MP4/i,
			},
			tips: { // 提示
				[ADVERT_TYPE_ID_VIDEO]: this.$t('advert.video_format'),
				[ADVERT_TYPE_ID_IMAGE]: this.$t('advert.image_format'),
			},

			TYPE_IMAGE: ADVERT_TYPE_ID_IMAGE,
			TYPE_VIDEO: ADVERT_TYPE_ID_VIDEO,
			REDIRECTABLE_TYPE_PACK,
			REDIRECTABLE_TYPE_PRODUCT,
			REDIRECTABLE_TYPE_URL,

			redirect_types: [
				{ name: this.$t('advert.redirect_pack'), id: REDIRECTABLE_TYPE_PACK },
				{ name: this.$t('advert.redirect_product'), id: REDIRECTABLE_TYPE_PRODUCT },
				{ name: this.$t('advert.redirect_url'), id: REDIRECTABLE_TYPE_URL },
			],
		};
	},
	computed: {
		accept() {
			const key = this.formValidate.advert_type_id;
			return this.accepts[key];
		},
		fileTypeRegExp() {
			const key = this.formValidate.advert_type_id;
			return this.regExps[key];
		},
		uploadTips() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},
	},

	watch: {
		'formValidate.advert_type_id': {
			handler() {
				this.removeFile();
			},
		},
	},

	methods: {
		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 重置 bos upload 组件
		 * @return {undefined}
		 */
		removeFile() {
			this.$refs.bos_upload.reset();
		},

		/**
     * bos上传进度显示
     * @param  {string} progress {需要设置给bos_key的值}
     * @return {undefined} {description}
     */
		changeProgress(progress) {
			const load_info = this.$t('advert.upload_progress', { value: progress });
			this.showSpin(load_info);
		},

		/**
     * 处理文件校验的结果
     * @param {boolean} isvalid
     */
		isValidateVideo() {
			// alert(`${isvalid}valid`);
		},

		/**
     * 设置bos_key
     * @param  {string} value {需要设置给bos_key的值}
     * @return {undefined} {description}
     */
		setBosKey(value) {
			this.formValidate.content_key = value;
		},

		/** *
		 * 上传完成回调
		 * @param {Object} object {上传结束文件对象}
		 * @return {undefined}
		 */
		handlePostComplete({ object }) {
			this.formValidate.content_key = object;
			if (this.formValidate.advert_type_id === ADVERT_TYPE_ID_VIDEO) {
				this.formValidate.play_second = 0;
				this.formValidate.redirectable_type = '';
			}
			this.post(deleteEmptyValue(this.formValidate))
				.then((result) => {
					if (result) { this.$Message.success(this.$t('common.operate_success')); }
					this.handleReset('formValidate');
				})
				.catch((error) => {
					this.$Message.error(error.message);
				})
				.then(() => {
					this.closeSpin();
				});
		},

		/**
		 * bos上传按钮组件初始化回调
		 * @return {undefined}
		 */
		init() {
			// console.log('Bos have been initialized');
		},

		/**
		 * 上传的过程中出错的回调
		 * @param  {type} error {错误信息}
		 * @return {undefined}
		 */
		handleError(error) {
			this.$Message.error(error.message);
		},

		/**
		 * 表单提交
		 * @param {String} name {表单上的ref值}
 		 */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.$refs.bos_upload.start();
				} else {
					this.$Message.error(this.$t('common.invalid_form_data'));
				}
			});
		},

		/**
		 * 表单重置
		 * @param  {String} name {表单上的ref的值}
		 * @return {undefined}
		 */
		handleReset(name) {
			this.removeFile();
			this.formValidate.device_account_ids = [];
			this.$refs[name].resetFields();
			this.formValidate.play_second = 15;
		},

		isAdvertTypeImage() {
		  return this.formValidate.advert_type_id === ADVERT_TYPE_ID_IMAGE;
		},

		/**
     * @return {boolean}
     */
		packSelectionVisible() {
			return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PACK
        && this.isAdvertTypeImage();
		},
		/**
     * @return {boolean}
     */
		assetSelectionVisible() {
			return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PRODUCT
        && this.isAdvertTypeImage();
		},
		/**
     * @return {boolean}
     */
		urlInputVisible() {
			return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_URL
			&& this.isAdvertTypeImage();
		},

		validateRedirectId(rule, value, callback) {
			if (this.formValidate.redirectable_type && !value) {
				callback(this.$t('validate.required', { field: this.$t('common.option') }));
			} else {
				callback();
			}
		},

		validateRedirectUrl(rule, value, callback) {
			const isRedirectTypeUrl = this.formValidate.redirectable_type === this.REDIRECTABLE_TYPE_URL;

			if (isRedirectTypeUrl && !isUrlValidate(value)) {
				callback(this.$t('validate.url', { field: this.$t('advert.redirect_url') }));
			} else {
				callback();
			}
		},
	},
};
</script>
